#!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>

from __future__ import (unicode_literals, division, absolute_import,
                        print_function)
import sys
import os
import errno
import subprocess

from vms import ensure_vm, shutdown_vm, Rsync, to_vm, from_vm, run_main, get_calibre_dir
VM = 'win-calibre-build'
rsync = Rsync(VM)
base = os.path.dirname(os.path.abspath(__file__))

if sys.argv[1:] == ['shutdown']:
    shutdown_vm(VM)
    raise SystemExit(0)


def abspath(x):
    return os.path.abspath(os.path.join(base, x))


def usage():
    raise SystemExit((
        'Usage: %s 32|64|shutdown'
        ' [the rest of the command line is passed to main.py]'
    ) % sys.argv[0])


arch = sys.argv[1].decode('utf-8')
if arch not in '64 32'.split() or len(sys.argv) < 2:
    usage()


def mkdir(x):
    try:
        os.mkdir(abspath(x))
    except EnvironmentError as err:
        if err.errno == errno.EEXIST:
            return
        raise


mkdir('sources-cache')
mkdir('build')
mkdir('build/win')
output_dir = os.path.join(abspath('build'), 'win', arch)
mkdir(output_dir)

ensure_vm(VM)

calibre_dir = get_calibre_dir()
if os.path.exists(os.path.join(calibre_dir, 'setup.py')):
    if 'calibre' in sys.argv and not os.path.exists(os.path.join(calibre_dir, 'icons', 'library.ico')):
        # Ensure .ico files are built
        print('Building .ico icons...')
        subprocess.check_call([sys.executable, os.path.join(calibre_dir, 'icons', 'make_ico_files.py')])

to_vm(rsync, output_dir, prefix='/cygdrive/c/', name='sw' + arch)
try:
    run_main(VM, 'python', '/scripts/main.py', *sys.argv[1:])
finally:
    print()
    from_vm(rsync, output_dir, prefix='/cygdrive/c/', name='sw' + arch)
